<template>
  <div class="app-container inden-manage sticky-box">
    <div>
      <avue-form
        :option="option"
        v-model="queryParams"
        ref="searchForm"
        v-show="showSearch"
        @keydown.enter="getList"
      >
        <!-- <template #customerId>
          <el-select
            class="w-full"
            v-model="queryParams.customerId"
            placeholder="请选择客户名称"
            @focus="selectCustomerFn('customerId')"
          >
            <el-option
              v-for="item in customerOption['customerId']"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select> -->
        <!-- <el-select
            v-model="queryParams.customerId"
            placeholder="请选择客户名称"
            class="w-full"
            filterable
            remote
            clearable
            :remote-method="queryCustomer"
            :loading="loadingSelect"
            no-data-text="未查询到客户"
          >
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            >
              <div>
                <span>{{ item.customerName }}</span>
              </div>
            </el-option>
          </el-select>
        </template> -->
        <template #menu-form>
          <el-button icon="Search" type="primary" @click="getList" class="m-l-3"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleEmpty(searchForm)"
            >重置</el-button
          >
        </template>
      </avue-form>

      <el-row :gutter="10" class="my-4">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="EditPen"
            plain
            @click="handleUpdate"
            :disabled="disUpdate"
            >编辑</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Delete"
            plain
            @click="handleDelete"
            :disabled="disDelete"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Upload"
            plain
            @click="
              () => {
                uploadDia.open = true
              }
            "
            >导入</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="primary" icon="Download" plain @click="exportDetail"
            >导出</el-button
          >
        </el-col> -->
        <!-- <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Aim"
            @click="apportionLog"
            :disabled="disDelete"
            >分配</el-button
          >
        </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Histogram"
            plain
            @click="handleStatistics"
            >统计</el-button
          >
        </el-col>
        <right-toolbar @queryTable="getList" v-model:showSearch="showSearch">
          <el-tooltip
            class="item"
            effect="dark"
            :content="'自定义列表'"
            placement="top"
          >
            <el-button circle icon="Menu" @click="handleTable()" />
          </el-tooltip>
        </right-toolbar>
      </el-row>

      <el-table
        class="sticky-table"
        v-loading="loading"
        :data="tableList"
        row-key="id"
        stripe
        border
        :scrollbar-always-on="true"
        @selection-change="handleSelectionChange"
        @row-dblclick="
          row => {
            goTo('/rsgl/other/knowledgeDetails', {
              knowledgeId: row.id
            })
          }
        "
      >
        <el-table-column
          type="selection"
          width="40"
          align="center"
          fixed="left"
        />
        <el-table-column
          v-for="(item, index) in tableCol.filter(item => item.show)"
          :key="index"
          v-bind="item"
        >
          <template #default="scope">
            <div v-if="item.tooltip">
              <el-tooltip
                :disabled="!scope.row.invoiceMsg"
                effect="dark"
                :content="item.tooltip(scope.row)"
                placement="top"
              >
                {{ item.tooltipVal(scope.row) }}
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="操作"
          align="center"
          width="220"
          fixed="right"
          class-name="small-padding"
        >
          <template #header>
            <div>操作</div>
          </template>
          <template #default="scope">
            <el-button
              plain
              size="small"
              type="primary"
              icon="Postcard"
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              @click="handleFollowUp(scope.row)"
              >跟进</el-button
            >
            <el-button
              plain
              size="small"
              type="primary"
              icon="Sort"
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              @click="handleFollowUpDia(scope.row)"
              >跟进记录</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 人员弹出框下拉框 -->
      <SelectDialog
        :dialog-param="dialogParam"
        @ok="selectDialogData"
        @close="
          val => {
            dialogParam.isDialog = false
          }
        "
      ></SelectDialog>

      <!-- 自定义订单列表弹窗 -->
      <DiaFixTable
        v-model="diaTable.open"
        :dialogParam="diaTable"
        @ok="diaTableFn"
      />

      <!-- 导入弹窗 -->
      <el-dialog
        :title="uploadDia.title"
        v-model="uploadDia.open"
        width="400px"
        append-to-body
        @close="closeUpload"
        :close-on-click-modal="false"
      >
        <el-upload
          v-loading="uploadLoading"
          action="#"
          :before-upload="rawFile => beforeAvatarUpload(rawFile, 'type01')"
          :http-request="params => requestFile(params, 'type01')"
          :accept="uploadType['type01'].toString()"
          :show-file-list="false"
          drag
        >
          <el-icon class="el-icon--upload">
            <upload-filled />
          </el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div>
              <div class="el-upload__tip text-center">
                <span class="text-red"
                  >仅允许导入{{ uploadType['type01'].toString() }}</span
                >
                <el-link
                  type="primary"
                  :underline="false"
                  style="font-size: 12px; vertical-align: baseline"
                  @click="downUrl"
                  >下载模板
                </el-link>
              </div>
              <div v-if="uploadDia.message" style="white-space: pre-line">
                导入结果：{{ uploadDia.message }}
              </div>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
            <el-button @click="closeUpload">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <!-- 跟进弹窗 -->
    <FollowUp
      :dialogParam="followUpParam"
      @close="
        () => {
          followUpParam.isVisible = false
        }
      "
    ></FollowUp>

    <!-- 跟进记录 -->
    <el-dialog
      :title="FollowUpDia.title"
      v-model="FollowUpDia.open"
      :width="FollowUpDia.width"
      append-to-body
      @close="closeFollowUpDia"
      :close-on-click-modal="false"
    >
      <FollowUpList :tableParam="FollowUpDia.tableParam" />
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
          <el-button @click="closeFollowUpDia">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 统计 -->
    <el-dialog
      :title="statisticsDia.title"
      v-model="statisticsDia.open"
      :width="statisticsDia.width"
      append-to-body
      @close="closeStatisticsDia"
      :close-on-click-modal="false"
    >
      <div>
        <el-row :gutter="20">
          <!--供应商列表-->
          <el-col :span="24">
            <el-form
              :model="queryParamsStatistics"
              ref="queryRef"
              :inline="true"
              label-width="0"
              @submit.prevent
              @keyup.enter="getListStatistics"
            >
              <div class="flex">
                <div class="w-6/24">
                  <el-form-item prop="source">
                    <el-select
                      clearable
                      class="w-full"
                      v-model="queryParamsStatistics.source"
                      placeholder="请选择数据来源"
                      @change="getListStatistics"
                    >
                      <el-option
                        v-for="item in knowledge_source"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div class="w-6/24">
                  <el-form-item prop="businessType">
                    <el-select
                      clearable
                      class="w-full"
                      v-model="queryParamsStatistics.businessType"
                      placeholder="请选择业务类型"
                      @change="getListStatistics"
                    >
                      <el-option
                        v-for="item in knowledge_business_type"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div class="w-6/24">
                  <el-form-item prop="type">
                    <el-select
                      class="w-full"
                      clearable
                      v-model="queryParamsStatistics.type"
                      placeholder="请选择所属分类"
                      @change="getListStatistics"
                    >
                      <el-option
                        v-for="item in knowledge_type"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div class="w-6/24">
                  <el-form-item prop="createTime">
                    <el-date-picker
                      style="width: 100%"
                      v-model="queryParamsStatistics.createTime"
                      type="daterange"
                      clearable
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      value-format="YYYY-MM-DD"
                      @change="getListStatistics"
                    />
                  </el-form-item>
                </div>
              </div>
            </el-form>
            <div>
              <span>数量：{{ dataListStatistics.num }}</span>
            </div>
            <!-- <el-table
              v-loading="loadingStatistics"
              :data="dataListStatistics"
              border
              stripe
              show-summary
              :sum-text="'统计'"
            >
              <el-table-column prop="dictLabel" label="业务类型">
              </el-table-column>
              <el-table-column prop="num" label="电话记录数"> </el-table-column>
              <el-table-column prop="commitNum" label="跟进数">
              </el-table-column>
            </el-table> -->
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
          <el-button @click="closeStatisticsDia">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="KnowledgeBase">
import { reactive, toRefs, ref, toRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  listKnowledge,
  listStatistics,
  delKnowledge,
  setKnowledge,
  importKnowledge,
  getKnowledgeDetail
} from '@/api/officeManage/knowledge'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import FollowUpList from '@/businessComponents/FollowUpList'
import FollowUp from '@/businessComponents/FollowUp'
import { treeselect } from '@/api/rsgl/zzjg'
import { getPricipalId, viewFile, initTable } from '@/utils/commo'
import { parseTime, selectDictLabel } from '@/utils/ruoyi'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
// 列表配置
const INITTABLE = [
  // {
  //   show: true,
  //   prop: 'registrationTime',
  //   label: '登记日期',
  //   align: 'center',
  //   width: 180,
  //   showOverflowTooltip: true
  //   // formatter: row => {
  //   //   return parseTime(row.repaymentDeadline, '{y}-{m}-{d}')
  //   // }
  // },
  {
    show: true,
    prop: 'phone',
    label: '来电号码',
    align: 'center',
    width: 160,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'content',
    label: '问题描述',
    align: 'center',
    minWidth: 160,
    showOverflowTooltip: false,
    formatter: row => {
      return row.content.replace(/<[^>]*>|<\/[^>]*>/gm, '')
    }
  },
  {
    show: true,
    prop: 'solution',
    label: '处理方案',
    align: 'center',
    minWidth: 160,
    showOverflowTooltip: false
    // formatter: row => {
    //   return row.content.replace(/<[^>]*>|<\/[^>]*>/gm, '')
    // }
  },
  {
    show: true,
    prop: 'site',
    label: '问题发生地',
    align: 'center',
    width: 130,
    showOverflowTooltip: true,
    formatter: row => {
      return selectDictLabel(problem_site.value, row.site)
    }
  },
  {
    show: true,
    prop: 'module',
    label: '所属模块',
    align: 'center',
    width: 130,
    showOverflowTooltip: true,
    formatter: row => {
      return selectDictLabel(knowledge_module.value, row.module)
    }
  },
  {
    show: true,
    prop: 'createName',
    label: '添加人',
    align: 'center',
    width: 100,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'createTime',
    label: '创建时间',
    align: 'center',
    width: 180,
    showOverflowTooltip: true
    // formatter: row => {
    //   return parseTime(row.createTime, '{y}-{m}-{d}')
    // }
  }
]

const commonStore = useCommonStore()

const btnLoadingArr = ref([])

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const {
  problem_site,
  knowledge_source,
  knowledge_business_type,
  knowledge_type,
  knowledge_module
} = proxy.useDict(
  'problem_site', //问题发生地
  'knowledge_source', //知识库来源
  'knowledge_business_type', //知识库业务类型
  'knowledge_type', //知识库所属分类
  'knowledge_module' //知识库中新增所属模块
)

const userOption = ref({ userId: [] })
const deptIdOption = ref([])
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  ids: [],
  selectArr: [],
  total: 0,
  option: {
    labelWidth: '10',
    menuSpan: 7,
    submitBtn: false,
    menuPosition: 'left',
    // gutter: 30,
    emptyBtn: false,
    column: [
      // {
      //   prop: 'registrationTimeArr',
      //   type: 'daterange',
      //   span: 6,
      //   format: 'YYYY-MM-DD',
      //   valueFormat: 'YYYY-MM-DD',
      //   startPlaceholder: '登记开始时间',
      //   endPlaceholder: '登记结束时间'
      // },
      // {
      //   prop: '_userId',
      //   span: 3,
      //   placeholder: '导入人',
      //   type: 'select',
      //   clearable: false,
      //   props: {
      //     value: 'uuid'
      //   },
      //   popperClass: 'className',
      //   dicData: computed(() => {
      //     return userOption.value['userId']
      //   }),
      //   multiple: false,
      //   click: ({ value, column }) => {
      //     dialogParam.value.type = 'userId'
      //     dialogParam.value.title = '请选择人员'
      //     dialogParam.value.isDialog = true
      //     dialogParam.value.multiple = false
      //     dialogParam.value.nodeKey = 'uuid'
      //     dialogParam.value.apiParams = { deptId: 100 }
      //     dialogParam.value.defaultCheckedKeys = [queryParams.value._userId]
      //     dialogParam.value.dataType = 'person'
      //   }
      // },
      {
        // label: '性别',
        span: 4,
        prop: 'businessType',
        placeholder: '业务类型',
        type: 'select',
        multiple: true,
        // filterable: true,//模糊搜索
        dicData: knowledge_business_type
      },
      {
        // label: '性别',
        span: 4,
        prop: 'content',
        placeholder: '问题描述',
        type: 'input'
      },
      {
        // label: '性别',
        span: 4,
        prop: 'source',
        placeholder: '来源',
        type: 'select',
        multiple: true,
        dicData: knowledge_source
      }
    ]
  },
  showSearch: true,
  disUpdate: true /* 编辑按钮是否可编辑 */,
  disDelete: true /* 关闭按钮是否可编辑 */,
  disTransfer: true /* 转入知识库是否可编辑 */,
  loading: false,
  tableList: [],
  dialogParam: {}
})
const {
  queryParams,
  ids,
  selectArr,
  total,
  option,
  showSearch,
  disUpdate,
  disDelete,
  disTransfer,
  loading,
  tableList,
  dialogParam
} = toRefs(data)
watch(
  [() => route.query.salesOrderData],
  async () => {
    if (route.query.salesOrderData) {
      queryParams.value = JSON.parse(route.query.salesOrderData)
      getList()
    }
  },
  {
    immediate: true
  }
)

const tableCol = ref(INITTABLE)
// 自定义列表弹窗参数
const diaTable = ref({
  open: false,
  // tableName:'',
  tableCol: []
})

// 自定义列表
const handleTable = () => {
  diaTable.value = {
    open: true,
    tableName: 'knowledgeBaseTable',
    tableCol: tableCol.value,
    initCol: INITTABLE
  }
}

// 获取列表配置
const diaTableFn = value => {
  tableCol.value = value
}

// 初始化
async function init() {
  // 初始化列表配置
  tableCol.value = initTable('knowledgeBaseTable', INITTABLE)

  // 归属部门
  getList()
}
// 获取部门树
const getDeptTree = () => {
  if (!queryParams.value.deptId) return
  queryParams.value.transactionDept = ''
  let data = { deptId: queryParams.value.deptId }
  treeselect(data).then(res => {
    deptIdOption.value = res.data
  })
}
getDeptTree()
// 重置
function handleEmpty(formEl) {
  console.log('queryParams.value1==>', toRaw(queryParams.value))
  proxy.resetForm('searchForm')
  proxy.resetForm('seniorSearchForm')
  // proxy.$refs.searchForm.resetForm()
  getList()
}

// 获取数据列表
function getList() {
  loading.value = true
  console.log('userOption.value==>', userOption.value)
  // 所属人员
  queryParams.value.userId = getPricipalId(
    userOption.value['userId'],
    queryParams.value._userId || ''
  ).toString()
  console.log('queryParams.value2==>', queryParams.value)
  listKnowledge(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
    console.log(' tableList.value==>', tableList.value)
  })
  console.log('获取数据')
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disUpdate.value = selection.length != 1
  disDelete.value = !selection.length
  let transfer = selection.some(item => item.isTransfer == '是')
  disTransfer.value = !selection.length || transfer
}

function goTo(url, data) {
  router.push({ path: url, query: data })
}
// 知识库分配给人员
const apportionUserIds = ref([])
const apportionLog = () => {
  dialogParam.value.type = 'apportionUser'
  dialogParam.value.title = '请选择人员'
  dialogParam.value.isDialog = true
  dialogParam.value.multiple = true
  dialogParam.value.nodeKey = 'uuid'
  dialogParam.value.apiParams = { deptId: 100 }
  // dialogParam.value.defaultCheckedKeys = apportionUserIds
  dialogParam.value.dataType = 'person'
}
/* 人员确认 */
const selectDialogData = val => {
  switch (val.type) {
    case 'userId':
      userOption.value.userId = val.selectData
      // queryOption.value.column[2].dicData = val.selectData
      queryParams.value._userId = val.defaultCheckedKeys.toString()
      break
  }
}

function handleAdd() {
  goTo('/rsgl/other/knowledgeForm', {})
}

function handleUpdate() {
  goTo('/rsgl/other/knowledgeForm', { knowledgeId: ids.value[0] })
}

// 删除
function handleDelete(row) {
  let rowIds = row.id || ids.value
  // console.log('selectArr-->', selectArr.value, 'id==>', rowIds)
  proxy.$modal
    .confirm('是否删除该知识库')
    .then(function () {
      return delKnowledge(rowIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

// 跟进
const followUpParam = ref({})
function handleFollowUp(row) {
  /***订单模块 */
  console.log('row==>', row)
  followUpParam.value.isVisible = true
  followUpParam.value.tableName = 'biz_telephone_record'
  followUpParam.value.businessId = row.id
}
// 跟进记录弹窗
const FollowUpDia = ref({
  title: '跟进记录',
  open: false,
  width: '1000px',
  tableParam: {}
})
const handleFollowUpDia = row => {
  FollowUpDia.value.open = true
  FollowUpDia.value.tableParam = {
    businessId: row.id, //业务id
    tableName: 'biz_telephone_record' //业务类型
  }
}
// 关闭导入弹窗
function closeFollowUpDia() {
  FollowUpDia.value.open = false
}

// 统计弹窗
const statisticsDia = ref({
  title: '统计',
  open: false,
  width: '1000px'
})
const loadingStatistics = ref(false)
const dataListStatistics = ref([])
// 统计
const handleStatistics = () => {
  queryParamsStatistics.value = {}
  statisticsDia.value.open = true
  getListStatistics()
}
const queryParamsStatistics = ref({})
const getListStatistics = () => {
  loadingStatistics.value = true
  listStatistics(queryParamsStatistics.value).then(res => {
    dataListStatistics.value = res.data
    loadingStatistics.value = false
  })
}
const closeStatisticsDia = () => {
  statisticsDia.value.open = false
}

/* 数据导入 开始 */
// 导入弹窗
const uploadDia = ref({
  title: '导入知识库',
  open: false,
  message: ''
})
const uploadType = {
  type01: ['.xls', '.xlsx'],
  type02: [
    '.rar',
    '.zip',
    '.doc',
    '.docx',
    '.pdf',
    '.xls',
    '.xlsx',
    '.ppt',
    '.pptx',
    '.gif',
    '.jpg',
    '.jpeg',
    '.png'
  ]
}
// 模板下载
const downUrl = async function downUrl() {
  const url = await commonStore.getUploadTemplateDown('knowledge_base_template')
  // console.info('url', url)
  window.open(url, '_blank')
}
/**导入数据 限制条件
 *
 * @param {*} rawFile
 */
const uploadLoading = ref(false)
function beforeAvatarUpload(rawFile, type) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = uploadType[type].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error(
      `上传文件只能是${uploadType[type]
        .toString()
        .replace(/\./g, '')
        .replace(/,/g, '、')}格式!`
    )
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传文件
async function requestFile(params, type) {
  uploadLoading.value = true
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  try {
    let res = await importKnowledge(uploadData)
    uploadLoading.value = false
    if (res.code === 200) {
      proxy.$modal.msgSuccess('导入成功')
      uploadDia.value.message = res.msg
      getList()
    }
  } catch (error) {
    uploadLoading.value = false
  }
}

// 导出明细
const exportDetail = () => {
  proxy.downLoadByUrl(
    '/customer/telephone/record/export',
    queryParams.value,
    '直销客户.xlsx'
  )
}

// 关闭导入弹窗
function closeUpload() {
  uploadDia.value.open = false
  uploadDia.value.message = ''
}
/* 数据导入 结束 */

init()
</script>
<style scoped lang="scss">
@import '@/assets/styles/myStyle.scss';
</style>
<style scoped lang="scss">
.search-drawer-retract {
  color: #999999;
}
</style>
